package com.xianzhiOA.controller;

import com.xianzhiOA.bean.*;
import com.xianzhiOA.service.XzPersonService;
import com.xianzhiOA.util.*;
import com.xianzhiOA.websocket.SocketMsgUtil;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.websocket.Session;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/3/31.
 */

@Controller
@RequestMapping("/Person")
@SessionAttributes({"userForeEnd","mySocket","searchPerson","searchPersonBack"})
public class XzPersonController{

    @InitBinder
    public void initBinder(WebDataBinder binder){
        //日期格式
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, true));
    }

    @Autowired
    XzPersonService personService;
    @RequestMapping("/addPerson.do")
    public ModelAndView addPerson(XzPerson person){
        ModelAndView mv = new ModelAndView("redirect:selPersonAll.do");
        person.setIsdelete(0);
        Date date = new Date();
        person.setCreateTime(date);
        Calendar now = Calendar.getInstance();
        int nowYear = now.get(Calendar.YEAR);
        if(person.getPersonBirth()!=null){
            String [] bb = person.getPersonBirth().split("-");
            String year = bb[0];
            person.setPersonBirth(bb[0]+"-"+bb[1]);
            person.setPersonAge(nowYear-Integer.parseInt(year));
        }
        personService.insert(person);
        return mv;
    }

    @RequestMapping("/selPersonAll.do")
    public ModelAndView selPersonAll(String isAll,XzPerson person,@RequestParam(defaultValue="0") int page,@RequestParam(defaultValue="10") int rows,Date begin,Date end,ModelMap model){
        ModelAndView mv = new ModelAndView("foreEnd/personShow");
        SearchBean<XzPerson> searchPerson = (SearchBean<XzPerson>) model.get("searchPerson");
        if(searchPerson==null){
            searchPerson = new SearchBean<>(person,page,rows);
            searchPerson.setBeginDate(begin);
            searchPerson.setEndDate(end);
        }else{
            if(isAll!=null&&isAll.equals("all")) {
                searchPerson.getEntity().setPersonReception(person.getPersonReception());
                searchPerson.getEntity().setPersonRecord(person.getPersonRecord());
                searchPerson.setBeginDate(begin);
                searchPerson.setEndDate(end);
            }
            searchPerson.makeSearch(person);
            if(page!=0)searchPerson.setPage(page);
            if(rows!=0)searchPerson.setRows(rows);
        }
        model.addAttribute("searchPerson",searchPerson);
        PageBean<XzPerson> pageBean = personService.selAll(searchPerson);
        //总页数
        int pages = pageBean.getPages();
        //当前页
        int pageNum = pageBean.getPageNum();
        //总条数
        long total = pageBean.getTotal();

        mv.addObject("personList",pageBean.getList());
        searchPerson.setPage(pageNum);
        mv.addObject("page",pageNum);
        mv.addObject("pages",pages);
        mv.addObject("total",total);
        mv.addObject("person",searchPerson.getEntity());
        mv.addObject("begin",searchPerson.getBeginDate());
        mv.addObject("end",searchPerson.getEndDate());
        return mv;
    }

    //编辑人员
    @RequestMapping("/editPerson.do")
    public ModelAndView editPerson(Long pid){
        ModelAndView mv = new ModelAndView("foreEnd/personEdit");
        XzPerson person;
        if(pid!=null&&pid!=0){
            person =  personService.findById(pid);
        }else{
            person = new XzPerson();
            person.setPersonAge(0);
            person.setPersonReception(2);
        }
        System.out.println(person);
        mv.addObject("person",person);
        return mv;
    }
    //单一简历导入
    /*@RequestMapping("/importPerson")
    public ModelAndView importPerson(@RequestParam(value = "file")MultipartFile file,Long id,String type){
        ModelAndView mv = new ModelAndView("redirect:selPersonAll.do");
        //读取配置文件
        String proFileName = "/config/upload.properties";
        Properties pro = readProperties(proFileName);
        //简历保存路径
        String original = pro.getProperty("originalB");
        //上传简历docx
        String filename = file.getOriginalFilename();
        String path = System.getProperty("xianzhi.path")+original;
        //设置文件名
        if(type.equals("zl")){
            filename = filename.split("_")[1];
        }else if(type.equals("qc")){
            filename = filename.split("_")[1];
        }
        Date date = new Date();
        String docName = date.getTime()+"_"+filename+".doc";
        File newFile = new File(path, docName);
        if(!newFile.exists()){
            newFile.mkdirs();
        }
        //转换pdf，并删除docx
        String pdfName = docName.replace(".docx",".pdf");
        if(newFile.exists()){
            ResumeToHtmlOrPdf.wordToPDF(path+docName,path+pdfName);
            newFile.delete();
        }
        XzPerson person = personService.findById(id);
        person.setPersonResume(pdfName);
        personService.updateByPrimaryKey(person);
        return  mv;
    }*/


    //人员认主
    @RequestMapping("/belongTo.do")
    public ModelAndView belongTo(Long personId, @ModelAttribute("userForeEnd")XzEmp userForeEnd){
        ModelAndView mv = new ModelAndView("redirect:selPersonAll.do");
        try{
            XzPerson person = personService.findById(personId);
            person.setEmpId(userForeEnd.getEmpId());
            person.setEmpName(userForeEnd.getEmpName());
            person.setPersonRecord(2);
            personService.updateByPrimaryKey(person);
            //通知其它用户更新认主状态
            SocketMsgUtil.msgGo("toUpdate",userForeEnd.getEmpId());
        }catch (Exception e){
            e.printStackTrace();
            mv.addObject("mag","error");
        }
        return mv;
    }
    //等级修改
    @RequestMapping("/updateAudit.do")
    @ResponseBody
    public Map<String ,Object> updateAudit(Long personId,String level){
        Map<String,Object> map = new HashMap<>();
        XzPerson person = personService.findById(personId);
        person.setPersonAudit(level);
        int i = personService.updateByPrimaryKey(person);
        if(i!=0){
            map.put("msg","ok");
        }else{
            map.put("msg","error");
        }
        return map;
    }
    //阶段修改
    @RequestMapping("/updateComment.do")
    public ModelAndView updateRecord(XzPerson updatePerson){
        ModelAndView mv = new ModelAndView("redirect:selPersonAll.do");
        XzPerson person = personService.findById(updatePerson.getPersonId());
        person.setPersonReception(updatePerson.getPersonReception());
        person.setPersonRecord(updatePerson.getPersonRecord());
        if(updatePerson.getInterviewTime()!=null){
            person.setInterviewTime(updatePerson.getInterviewTime());
        }
        if(person.getCommentTime()==null){
            person.setCommentTime(new Date());
        }
        int i = personService.updateByPrimaryKey(person);
        return mv;
    }
    //单体导入
    @RequestMapping("/importPerson.do")
    public ModelAndView importPerson(Long personId,MultipartFile file){
        ModelAndView mv = new ModelAndView("redirect:selPersonAll.do");
        //读取配置文件
        String proFileName = "/config/upload.properties";
        Properties pro = readProperties(proFileName);
        //简历保存路径
        String original = pro.getProperty("originalB");
        String path = System.getProperty("xianzhi.path")+original;
        //文件名
        String fileName = file.getOriginalFilename();
        String docName = new Date().getTime()+"_"+fileName+".doc";
        File newFile = new File(path, docName);
        if(!newFile.exists()){
            newFile.mkdirs();
        }
        try {
            file.transferTo(newFile);
            String pdfName = docName.substring(0,docName.indexOf(".doc"))+".pdf";
            ResumeToHtmlOrPdf.wordToPDF(path+docName,path+pdfName);
            newFile.delete();
            XzPerson person = personService.findById(personId);
            person.setPersonResume(pdfName);
            personService.updateByPrimaryKey(person);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mv;
    }

    //批量导入
    @RequestMapping("/importPersonbatch.do")
    public ModelAndView importPersonbatch(@RequestParam(value = "files[]")MultipartFile [] files, String type){
        ModelAndView mv = new ModelAndView("redirect:selPersonAll.do");
        //读取配置文件
        String proFileName = "/config/upload.properties";
        Properties pro = readProperties(proFileName);
        //简历保存路径
        String original = pro.getProperty("originalB");
        String path = System.getProperty("xianzhi.path")+original;
        //excel文件集合
        List<File> excelFiles = new ArrayList<>();
        //world文件集合
        Map<String,File> worldFiles = new HashMap<>();
        //文件归类
        for (MultipartFile file : files) {
            //解析判断文件后缀
            String filename = file.getOriginalFilename();
            CommonsMultipartFile cf= (CommonsMultipartFile)file;
            DiskFileItem fi = (DiskFileItem)cf.getFileItem();
            File f = fi.getStoreLocation();
            if(filename.endsWith(".xls")){
                excelFiles.add(f);
            }else if(filename.endsWith(".doc")){
                if(type.equals("zl")){
                    filename = filename.split("_")[1];
                }else if(type.equals("qc")){
                    filename = filename.split("_")[1];
                }
                System.out.println(filename);
                String docName = new Date().getTime()+"_"+filename+".doc";
                File newFile = new File(path, docName);
                if(!newFile.exists()){
                    newFile.mkdirs();
                }
                try {
                    file.transferTo(newFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                worldFiles.put(filename,newFile);
            }
        }
        int count = personService.insertBatch(excelFiles,worldFiles,type,path);
        System.out.println("上传简历"+count+"份");
        mv.addObject("count",count);
        //mv.addObject("unCount",worldFiles.size()-count);
        return  mv;
    }
    //数据统计
    @RequestMapping("/Census.do")
    public ModelAndView census(Long cEmpId,String cEmpName,@RequestParam(defaultValue="cbsc")String type,@RequestParam(defaultValue="month")String cycle,Date selTime,@ModelAttribute("userForeEnd")XzEmp userForeEnd){
        ModelAndView mv = new ModelAndView("foreEnd/personCensus");
        if(selTime==null){
            selTime = new Date();
        }
        if(cEmpId==null||cEmpName==null){
            cEmpId = userForeEnd.getEmpId();
            cEmpName = userForeEnd.getEmpName();
        }

        Map<String,Object> map = new HashMap<>();
        if(!cEmpName.equals("总体")){
            map.put("empId",cEmpId);
        }
        map.put("myDate",selTime);
        if(cycle.equals("month")){
            map.put("month","go");
        }
        if(type.equals("cbsc")){
            map.put("reception","1");
            List<DateResult> dd1 = personService.selectAchievement(map);
            List<Integer> rs1 = makeRs(dd1,cycle);
            System.out.println(rs1);
            mv.addObject("rs1",rs1);
            map.put("reception","2");
            List<DateResult> dd2 = personService.selectAchievement(map);
            List<Integer> rs2 = makeRs(dd2,cycle);
            System.out.println(rs2);
            mv.addObject("rs2",rs2);
        }else if(type.equals("hqgz")){
            map.put("record","1");
            List<DateResult> dd1 = personService.selectAchievement(map);
            List<Integer> rs1 = makeRs(dd1,cycle);
            System.out.println(rs1);
            mv.addObject("rs1",rs1);
            map.put("record","2");
            List<DateResult> dd2 = personService.selectAchievement(map);
            List<Integer> rs2 = makeRs(dd2,cycle);
            System.out.println(rs2);
            mv.addObject("rs2",rs2);
            map.put("record","3");
            List<DateResult> dd3 = personService.selectAchievement(map);
            List<Integer> rs3 = makeRs(dd3,cycle);
            System.out.println(rs3);
            mv.addObject("rs3",rs3);
            map.put("record","4");
            List<DateResult> dd4 = personService.selectAchievement(map);
            List<Integer> rs4 = makeRs(dd4,cycle);
            System.out.println(rs4);
            mv.addObject("rs4",rs4);
        }
        mv.addObject("cEmpId",cEmpId);
        mv.addObject("type",type);
        mv.addObject("cycle",cycle);
        mv.addObject("cEmpName",cEmpName);
        mv.addObject("selTime",selTime);
        return mv;
    }
    //修改返回数据
    private List<Integer> makeRs(List<DateResult> drl,String cycle){
        //map装载 数字key（按月或日期）：计数count
        Map<Integer,Object> map = new HashMap<>();
        Calendar cal = Calendar.getInstance();
        for (DateResult dateResult : drl) {
            Date dr = dateResult.getrDate();
            cal.setTime(dr);
            int key = 0;
            if(cycle.equals("month")){
                key = cal.get(Calendar.DATE);
            }else{
                key = cal.get(Calendar.MONTH);
            }
            map.put(key,dateResult.getpCount());
        }
        //数组装载
        List<Integer> rs = new ArrayList<>();
        int die = 12;
        if(cycle.equals("month")){
            die = 31;
        }
        for (int i = 0; i < die; i++) {

            Integer count = (Integer) map.get(cycle.equals("month")?(i+1):i);
            if(count!=null){
                rs.add(count);
            }else{
                rs.add(0);
            }
        }
        return rs;
    }


    //验证认主
    /*@RequestMapping("/belong.do")
    @ResponseBody
    public Map<String,Object> belong(Long personId){
        Map<String,Object> map = new HashMap<>();
        try{
            XzPerson person = personService.findById(personId);

            map.put("msg","ok");
        }catch (Exception e){
            e.printStackTrace();
            map.put("mag","error");
        }
        return map;
    }*/
    //按他
    @RequestMapping("/editComment.do")
    public ModelAndView editComment(Long personId,boolean again){
        ModelAndView mv = new ModelAndView("foreEnd/editComment");
        XzPerson personComment = personService.findByIdForComment(personId);
        if(again){
            personComment.setPersonRecord(2);
            XzPerson updateP = personService.findById(personId);
            updateP.setPersonRecord(2);
            personService.updateByPrimaryKey(updateP);
        }
        mv.addObject("person",personComment);
        return mv;
    }

    private Properties readProperties(String proFileName){
        Properties pro = null;
        try {
            pro = new Properties();
            InputStream in = XzPersonController.class.getResourceAsStream(proFileName);
            pro.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  pro;
    }

    //显示pdf简历
    /*@RequestMapping("/showPdf")
    @ResponseBody
    public void showPdf(Long personId,HttpServletRequest request,HttpServletResponse response){
        //读取配置文件
        String proFileName = "/config/upload.properties";
        Properties pro = readProperties(proFileName);
        //简历保存路径
        String original = pro.getProperty("original");
        //上传简历docx
        String path = request.getServletContext().getRealPath(original);
        response.setContentType("application/pdf");
        PrintWriter out = null;
        //获取文件名
        XzPerson person = personService.findById(personId);
        String pdfName = person.getPersonResume();
        response.setHeader("Content-Disposition","attachment;filename="+pdfName);
        if(pdfName!=null&& !pdfName.equals("")){
            try {
                out = response.getWriter();
                //判断该路径下的文件是否存在
                File file = new File(path+pdfName);
                if (file.exists()) {
                    DataOutputStream temps = new DataOutputStream(response
                            .getOutputStream());
                    DataInputStream in = new DataInputStream(
                            new FileInputStream(file));

                    byte[] b = new byte[2048];
                    while ((in.read(b)) != -1) {
                        temps.write(b);
                        temps.flush();
                    }
                    in.close();
                    temps.close();
                } else {
                    out.print(pdfName + " 文件不存在!");
                }

            } catch (Exception e) {
                out.println(e.getMessage());
            }
        }else{
            try {
                out = response.getWriter();
                out.print(pdfName + " 文件不存在!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }*/
    ///////////////////////////后台方法/////////////////////////////
    //全查
    @RequestMapping("selPersonAll.emp")
    public ModelAndView selPersonAllForEmp(String isAll,XzPerson person,@RequestParam(defaultValue="0") int page,@RequestParam(defaultValue="10") int rows,Date begin,Date end,ModelMap model){
        ModelAndView mv = new ModelAndView("backEnd/personShow");
        SearchBean<XzPerson> searchPerson = (SearchBean<XzPerson>) model.get("searchPersonBack");

        if(searchPerson==null){
            searchPerson = new SearchBean<>(person,page,rows);
            searchPerson.setBeginDate(begin);
            searchPerson.setEndDate(end);
        }else{
            if(isAll!=null&&isAll.equals("all")) {
                searchPerson.getEntity().setPersonReception(person.getPersonReception());
                searchPerson.getEntity().setPersonRecord(person.getPersonRecord());
                searchPerson.setBeginDate(begin);
                searchPerson.setEndDate(end);
            }
            searchPerson.makeSearch(person);
            if(page!=0)searchPerson.setPage(page);
            if(rows!=0)searchPerson.setRows(rows);
        }
        System.out.println(searchPerson);
        model.addAttribute("searchPersonBack",searchPerson);
        PageBean<XzPerson> pageBean = personService.selAll(searchPerson);
        //总页数
        int pages = pageBean.getPages();
        //当前页
        int pageNum = pageBean.getPageNum();
        //总条数
        long total = pageBean.getTotal();

        mv.addObject("personList",pageBean.getList());
        searchPerson.setPage(pageNum);
        mv.addObject("page",pageNum);
        mv.addObject("pages",pages);
        mv.addObject("total",total);
        mv.addObject("person",searchPerson.getEntity());
        mv.addObject("begin",searchPerson.getBeginDate());
        mv.addObject("end",searchPerson.getEndDate());
        return mv;
    }
    //删除
    @RequestMapping("/deletePerson.emp")
    public ModelAndView deletePerson(Long personId){
        ModelAndView mv = new ModelAndView("redirect:selPersonAll.emp");
        int i = personService.deletePerson(personId);
        if(i==0){
            mv.addObject("msg","error");
        }else{
            mv.addObject("msg","ok");
        }
        return mv;
    }
    //编辑人员
    @RequestMapping("/editPerson.emp")
    public ModelAndView editPersonForEnd(Long pid){
        ModelAndView mv = new ModelAndView("backEnd/personEdit");
        XzPerson person;
        if(pid!=null&&pid!=0){
            person =  personService.findById(pid);
        }else{
            person = new XzPerson();
            person.setPersonReception(2);
        }
        System.out.println(person);
        mv.addObject("person",person);
        return mv;
    }
    //修改or添加
    @RequestMapping("/savePerson.emp")
    public ModelAndView savePerson(XzPerson person){
        ModelAndView mv = new ModelAndView("redirect:selPersonAll.emp");
        int i = 0;
        if(person.getPersonId()!=null&&person.getPersonId()!=0){
            i = personService.updateByPrimaryKeySelective(person);
        }else{
            person.setIsdelete(0);
            Date date = new Date();
            person.setCreateTime(date);
            Calendar now = Calendar.getInstance();
            int nowYear = now.get(Calendar.YEAR);
            if(person.getPersonBirth()!=null){
                String [] bb = person.getPersonBirth().split("-");
                String year = bb[0];
                person.setPersonBirth(bb[0]+"-"+bb[1]);
                person.setPersonAge(nowYear-Integer.parseInt(year));
            }
            personService.insert(person);
        }
        if(i==0){
            mv.addObject("msg","ok");
        }else{
            mv.addObject("msg","error");
        }
        return mv;
    }
}
